// component/cs-bg.js
import config from '../utils/config.js'
import util from '../utils/util.js'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    order: {
      type: Boolean,
      value: false
    }
  },
  observers: {
    'order': function (num) {
      console.log(num)
      this.setData({
        orderD: num
      }, () => {
        console.log(this.data.order)
        setTimeout(() => {
          if (this.data.orderD) {
            this.setData({
              second: true
            })
          }
        }, 2000)
      })
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    width: '',
    height: '',
    roundArr: [],
    orderD: false,
    second: false,
    endPage: false,
    nowDate: "2021-10-18",//util.formatTime(new Date()).split(' ')[0],
    endDate:"2021-10-21",
    canInput: true,
    second1:true,
    form: {
      is_mp: false,
      is_zs: false,
      name: '',
      mobile: '',
      email: '',
      company: '',
      comeday: '',
      leaveday: '',
      is_dy:0
    },
  },
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function () {},
    moved: function () {},
    detached: function () {},
  },
  ready() {
    wx.getSystemInfo({
      success: (result) => {
        this.setData({
          width: result.windowWidth,
          height: result.windowHeight,
        }, () => {
          setTimeout(() => {
            this.handleRound()
          }, 300)
        })
      },
    })
    this.getUserInfo()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    colseAuthPhone() {},
    /**
     * 获取用户手机号
     */
    getUserPhone(e) {
      console.log(e);
      if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
        // 用户拒绝授权
        this.setData({
          canInput: false
        });
      } else {
        this.initUserPhone(e);
      }
    },
    initUserPhone(data) {
      let a = data.detail;
      let url = config.getPhone;
      let o = {
        session3rd: wx.getStorageSync('session3rd'),
        encryptedData: a.encryptedData,
        iv: a.iv
      };
      util.ajax(url, o, (res)=> {
        if (res.data.code == 0) {
          let json = this.data.form
          json.mobile = res.data.data.mobile
          this.setData({
            form:json
          })
          wx.setStorageSync('mobile', res.data.data.mobile);
        }
      });
      this.setData({
        canInput: false
      });

    },
    bindDateChangeComeday: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      let form = this.data.form
      form.comeday = e.detail.value
      this.setData({
        form: form
      })
    },
    bindDateChangeLeaveday: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      let form = this.data.form
      form.leaveday = e.detail.value
      this.setData({
        form: form
      })
    },
    async sureOrder() {
      console.log(this.data.form)
      // 自定义一个事件，并且传值
      let o = this.data.form,
          url = config.submitOrder
      o.session3rd = wx.getStorageSync('session3rd')
      if (!o.name) {
        wx.showToast({
          title: '请填写姓名',
          icon: 'none'
        })
        return
      }
      if (!o.company) {
        wx.showToast({
          title: '请填写公司',
          icon: 'none'
        })
        return
      }
      if (!o.email) {
        wx.showToast({
          title: '请填写邮箱',
          icon: 'none'
        })
        return
      }
      if(o.email.indexOf('@') < 0 || o.email.indexOf('.') < 0){
        wx.showToast({
          title: '邮箱格式错误',
          icon: 'none'
        })
        return
      }
      if (!o.mobile) {
        wx.showToast({
          title: '请填写手机号',
          icon: 'none'
        })
        return
      }

      if(o.mobile.length != 11){
        wx.showToast({
          title: '手机号格式错误',
          icon: 'none'
        })
        return
      }

      if (o.is_zs) {
        if (!o.comeday) {
          wx.showToast({
            title: '请选择入住日期',
            icon: 'none'
          })
          return
        }
        if (!o.comeday) {
          wx.showToast({
            title: '请选择退房日期',
            icon: 'none'
          })
          return
        }
        var oDate1 = new Date(o.comeday);
        var oDate2 = new Date(o.leaveday);
        if(oDate1.getTime() > oDate2.getTime()){
          wx.showToast({
            title: '入住日期不能大于退房日期',
            icon: 'none'
          })
          return
        }
      }
      let r
      if (o.is_dy == 0) {
        r = await this.subscribeMessage()
      } else {
        r = o.is_dy
      }
      o.is_zs = o.is_zs ? 1:0
      o.is_mp = o.is_mp ? 1:0
      delete o.daycount
      delete o.unionid
      delete o.dengji_time
      delete o.create_time
      o.is_dy = r
      util.ajax(url, o, (res) => {
        if (res.data.code == 0) {
          util.showSuccess('登记成功')
          setTimeout(()=>{
            this.setData({
              endPage: true
            })
          },500)
        }else{
          util.alert(res.data.message)
        }
      })
    },
    subscribeMessage() {
      return new Promise((r) => {
        //需要订阅的消息模板，在微信公众平台手动配置获取模板ID
        let message = 'nwPFpA7RTtfZR84nL-OUk8mVyiAIM8cPqXNH_-t5a_o'
        //如果总是拒绝（subscriptionsSetting，2.10.1库才支持）
        if (this.versionCompare('2.10.1')) {
          wx.getSetting({
            withSubscriptions: true, //是否同时获取用户订阅消息的订阅状态，默认不获取
            success: (res) => {
              console.log(res)
              if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
                  res.subscriptionsSetting.itemSettings[message] == "reject") {
                //打开设置去设置
                this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
              } else {
                wx.requestSubscribeMessage({
                  tmplIds: [message],
                  success: (res) => {
                    console.log(res, 'sss')
                    if (res[message] == 'accept') {
                      //用户允许
                      console.log(res, 'sss')
                      r(1)
                    }else{
                      r(0)
                    }
                  },
                  fail: (res) => {
                    console.info(res)
                    r(0)
                  },
                })
              }
            }
          })
        } else if (this.versionCompare('2.4.4')) {
          wx.requestSubscribeMessage({
            tmplIds: [message],
            success: (res) => {
              console.log(res, 'sss')
              if (res[message] == 'accept') {
                //用户允许
                console.log(res, 'sss')
                r(1)
              }else{
                r(0)
              }
            },
            fail: (res) => {
              console.info(res)
              r(0)
            },
          })
        }
      })
    },
    //打开设置
    openConfirm(message) {
      wx.showModal({
        content: message,
        confirmText: "确认",
        cancelText: "取消",
        success: (res) => {
          //点击“确认”时打开设置页面
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                console.log(res.authSetting)
              },
              fail: (error) => {
                console.log(error)
              }
            })
          } else {
            console.log('用户点击取消')
          }
        }
      });
    },
    //基础库版本比较
    versionCompare(v) {
      const version = wx.getSystemInfoSync().SDKVersion
      if (this.compareVersion(version, v) >= 0) {
        return true
      } else {
        return false
      }
    },
    compareVersion: function (v1, v2) {
      v1 = v1.split('.')
      v2 = v2.split('.')
      var len = Math.max(v1.length, v2.length)

      while (v1.length < len) {
        v1.push('0')
      }
      while (v2.length < len) {
        v2.push('0')
      }

      for (var i = 0; i < len; i++) {
        var num1 = parseInt(v1[i])
        var num2 = parseInt(v2[i])

        if (num1 > num2) {
          return 1
        } else if (num1 < num2) {
          return -1
        }
      }
      return 0
    },
    getInputVal(e) {
      let type = e.currentTarget.dataset.type
      let val = e.detail.value
      let json = this.data.form
      switch (type) {
        case 'name':
          json.name = val
          this.setData({
            form: json
          })
          break;
        case 'mobile':
          json.mobile = val
          this.setData({
            form: json
          })
          break;
        case 'email':
          json.email = val
          this.setData({
            form: json
          })
          break;
        case 'company':
          json.company = val
          this.setData({
            form: json
          })
          break;
      }

      console.log(this.data.form)
    },
    changeDays(e) {
      let type = e.currentTarget.dataset.type
      let json = this.data.form
      if (type == "sub") {
        if (json.day == 1) {
          wx.showToast({
            title: '最少天数为1天',
            icon: 'none'
          })
          return
        }
        json.day--
        this.setData({
          form: json
        })
      } else {
        json.day++
        this.setData({
          form: json
        })
      }
    },
    changeSwitch(e) {
      let type = e.currentTarget.dataset.type
      let json = this.data.form
      if (type == "ticket") {
        json.is_mp = !json.is_mp
        this.setData({
          form: json
        })
      } else {
        json.is_zs = !json.is_zs
        this.setData({
          form: json,
          second1:false
        })
      }
      console.log(this.data.form)
    },
    handleRound() {
      let roundArr = []
      for (let i = 0; i < 50; i++) {
        let o = {
          width: i * (i + 3),
          height: i * (i + 3)
        }
        roundArr.push(o)
      }
      this.setData({
        roundArr: roundArr
      })
    },
    getUserInfo() {
      let url = config.user_info
      let o = {
        session3rd: wx.getStorageSync('session3rd')
      }
      util.ajax(url, o, (res) => {
        if (res.data.code == 0) {
          let data = res.data.data
          data.mobile = data.mobile2
          // data.comeday = data.comeday ? data.comeday : ''
          // data.leaveday = data.leaveday ? data.leaveday : ''
          if(data.mobile2){
            this.setData({
              canInput:false
            })
          }
          this.setData({
            form: {...data}
          })
        }
      })
    },
  }
})